﻿using FileSynchronizationClient.Models;
using Newtonsoft.Json;

namespace FileSynchronizationClient.Common
{
    /// <summary>
    /// Setting
    /// </summary>
    public class SettingMap
    {
        /// <summary>
        /// 发布类型
        /// </summary>
        public int Type { get; set; }

        /// <summary>
        /// 项目特定文件名字
        /// </summary>
        public string UniqueFileName { get; set; }

        /// <summary>
        /// 打包命令
        /// </summary>
        public string BuildCMD { get; set; }

        /// <summary>
        /// 打包地址
        /// </summary>
        public string DistPath { get; set; }

        /// <summary>
        /// 是否替换DistPath
        /// </summary>
        public bool ReplaceDistPath { get; set; }
    }

    /// <summary>
    /// 发布配置文件
    /// </summary>
    public class SettingMaps
    {
        private CommonHttpClient _commonHttpClient;
        public SettingMaps(CommonHttpClient commonHttpClient)
        {
            _commonHttpClient = commonHttpClient;
            InitSetting();
        }

        public List<SettingMap> List { get; set; }

        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <param name="publishType"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public SettingMap GetMap(int publishType)
        {
            var map = List.FirstOrDefault(s => s.Type == publishType);
            if (map is null)
                throw new Exception("请联系管理员添加发布类型");

            if (map.ReplaceDistPath)
                map.BuildCMD = map.BuildCMD.Replace("{DistPath}", map.DistPath);

            return map;
        }

        /// <summary>
        /// Init
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private void InitSetting()
        {
            var setting = _commonHttpClient.GetPublishSetting().Result;
            if (setting is null)
                throw new Exception("PublishSetting获取异常，请联系管理员");

            List = JsonConvert.DeserializeObject<List<SettingMap>>(JsonConvert.SerializeObject(setting.Data));
#if DEBUG
            var one = List.Where(s => s.Type == (int)PublishType.WeChatService).First();
            one.BuildCMD = $@"d: & cd D:\work\Wechat_PublicNumber & {one.BuildCMD}";
#endif
        }
    }
}
